package com.hd.crdao.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.activity.ConsumerDetailsActivity;
import com.hd.crdao.activity.PurchasedMealActivity;
import com.hd.crdao.adapter.MealListAdapter;
import com.hd.crdao.base.BaseFragment;
import com.hd.crdao.bean.MealListBean;
import com.hd.crdao.bean.MealWXPayBean;
import com.hd.crdao.bean.RechargeBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.PayResult;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.view.MyListView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Administrator
 *@date 2017/6/26 0026
 */
public class SetMealFrangment extends BaseFragment {
    @BindView(R.id.head)
    ExpandHeadView mHead;
    @BindView(R.id.tv_desc)
    TextView mTvDesc;
    @BindView(R.id.report_count)
    TextView mReportCount;
    @BindView(R.id.list_meal)
    MyListView mListMeal;
    public MealListBean mMealListBean;
    public String mBusinessid;
    public RechargeBean mRechargeBean;
    public MealListAdapter mMealListAdapter;
    //商户APP工程中引入微信JAR包，调用API前，需要先向微信注册您的APPID，代码如下
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(UIUtils.getContext(), null);

    private static final int SDK_PAY_FLAG = 1;
    //    private static final int SDK_AUTH_FLAG = 2;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(UIUtils.getContext(), "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(UIUtils.getContext(), "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
            }
        }
    };
    public CompoundButton.OnCheckedChangeListener mListener;
    public int mCaTimes;
    public String mCarAccountId;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_setmeal;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this, mViewRoot);
    }

    @Override
    protected void initListener() {
        mHead.getLeftArrowLL().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        mHead.getHeadViewRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               startActivity(new Intent(UIUtils.getContext(),ConsumerDetailsActivity.class));
            }
        });

        mListMeal.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                position = position -1;
                showPayPopWindow(position);
            }
        });

        mListMeal.setonRefreshListener(new MyListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData();
                mHandler.postDelayed(new LoadRunnale(), 1500);
            }
        });
    }



    @Override
    protected void initData() {
        mBusinessid = SPUtils.getString("businessid", "");
        loadData();
    }

    private void loadData() {
        OkHttpUtils.post().url(Constants.MEALLIST_URL).addParams("sign",Constants.SIGN).addParams("carBusinessId", mBusinessid)
                .addParams("serviceTypeId","1").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("加载数据失败,请检查网络...");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                Gson gson= new Gson();
                mMealListBean = gson.fromJson(response, MealListBean.class);
                String success = mMealListBean.getSuccess();
                String message = mMealListBean.getMessage();
                if(TextUtils.equals("00",success)){
                    List<MealListBean.CbAccountsBean> cbAccounts = mMealListBean.getCbAccounts();
                    if(cbAccounts.size()!= 0){
                        mCaTimes = cbAccounts.get(0).getCaTimes();
                        mCarAccountId =cbAccounts.get(0).getId();
                        ALog.d("caTimes==============="+ mCaTimes);
                        mReportCount.setText("报告剩余"+ mCaTimes +"条");
                    }
                    List<MealListBean.DataBean> data = mMealListBean.getData();
                    mMealListAdapter = new MealListAdapter(data);
                    mListMeal.setAdapter(mMealListAdapter);
                }else {
                    MyToast.show(message);
                }
            }
        });
    }


    @OnClick(R.id.report_count)
    public void onViewClicked() {
        if(mCaTimes!=0){
            Intent i = new Intent(UIUtils.getContext(),PurchasedMealActivity.class);
            i.putExtra("carAccountId",mCarAccountId);
            i.putExtra("CaTimes",mCaTimes);
            startActivity(i);
        }
    }

    /**
     * 弹出支付的popwindow
     * @param position
     */
    private void showPayPopWindow(final int position) {
        View parent = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(getActivity(), R.layout.pop_topay, null);
        ImageView imageView = (ImageView) popView.findViewById(R.id.dissmis);
        final CheckBox cbAlipay = (CheckBox) popView.findViewById(R.id.cb_alipay);
        final CheckBox cbWeixin = (CheckBox) popView.findViewById(R.id.cb_weixin);
        Button btnPay = (Button) popView.findViewById(R.id.pay);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        //设置监听
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        mListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switch (buttonView.getId()) {
                    case R.id.cb_alipay:
                        if (isChecked) {
                            cbAlipay.setChecked(true);
                            cbWeixin.setChecked(false);
                        }
                        break;
                    case R.id.cb_weixin:
                        if (isChecked) {
                            cbWeixin.setChecked(true);
                            cbAlipay.setChecked(false);
                        }
                        break;
                }
            }
        };
        cbWeixin.setOnCheckedChangeListener(mListener);
        cbAlipay.setOnCheckedChangeListener(mListener);
        btnPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(cbAlipay.isChecked()){
                    ToAliPay(position);
                    popWindow.dismiss();
                }else if(cbWeixin.isChecked()) {
                    if (! msgApi.isWXAppInstalled()) {
                        MyToast.show("请前往应用商店下载微信");
                    } else if (!msgApi.isWXAppSupportAPI()) {
                        MyToast.show("当前版本微信不支持支付");
                    }else {
                        ToWeixinPay(position);
                        popWindow.dismiss();
                    }
                }
            }
        });
    }
    /**
     *跳转到微信支付
     * @param position 套餐listview条目的position   要根据这个获取相关请求参数
     */
    private void ToWeixinPay(int position) {
        OkHttpUtils.post().url(Constants.RECHARGE_URL).addParams("sign", Constants.SIGN).addParams("carBusinessId", mBusinessid)
                .addParams("serviceTypeId", "1").addParams("serviceDetailId", mMealListBean.getData().get(position).getId())
                .addParams("plMethod", "W").addParams("system","Android").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("加载数据失败,请检查网络...");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                Gson gson = new Gson();
                MealWXPayBean mealWXPayBean = gson.fromJson(response, MealWXPayBean.class);
                String success = mealWXPayBean.getSuccess();
                String message = mealWXPayBean.getMessage();
                if(TextUtils.equals("00",success)){
                    MealWXPayBean.WxmessageBean wxmessage = mealWXPayBean.getWxmessage();
                    //调起支付
                    PayReq request = new PayReq();
                    request.appId = wxmessage.getAppid();
                    request.partnerId = wxmessage.getPartnerid();
                    request.prepayId= wxmessage.getPrepayid();
                    request.packageValue = wxmessage.getPackageX();
                    request.nonceStr=wxmessage.getNoncestr();
                    request.timeStamp= String.valueOf(wxmessage.getTimestamp());
                    request.sign= wxmessage.getSign();
                    // 将该app注册到微信
                    msgApi.registerApp(Constants.APP_ID);
                    msgApi.sendReq(request);

                }else {
                    MyToast.show(message);
                }

            }
        });
    }

    /**
     * 跳到支付宝支付
     * @param position  套餐listview条目的position   要根据这个获取相关请求参数
     */
    private void ToAliPay(int position) {
        OkHttpUtils.post().url(Constants.RECHARGE_URL).addParams("sign",Constants.SIGN).addParams("carBusinessId", mBusinessid)
                .addParams("serviceTypeId","1").addParams("serviceDetailId",mMealListBean.getData().get(position).getId())
                .addParams("plMethod","Z").addParams("system","Android").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("加载数据失败,请检查网络...");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                Gson gson= new Gson();
                mRechargeBean = gson.fromJson(response, RechargeBean.class);
                final String orderInfo = mRechargeBean.getOrderId();   // 订单信息
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(getActivity());
                        Map<String, String> result = alipay.payV2(orderInfo,true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        });
    }

    class LoadRunnale implements Runnable {
        @Override
        public void run() {
            //加载数据
            loadData();
            if (mMealListAdapter != null) {
                mMealListAdapter.notifyDataSetChanged();
                mListMeal.onRefreshComplete();
            }
        }
    }
}
